package com.nebula.salary.portal.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nebula.salary.common.constants.ReturnMessage;
import com.nebula.salary.common.exception.CustomException;
import com.nebula.salary.common.exception.ErrorException;
import com.nebula.salary.common.result.ServerResponse;
import com.nebula.salary.common.utils.SecurityUtil;
import com.nebula.salary.model.dto.WorkOvertimeDto;
import com.nebula.salary.model.pojo.WorkOvertime;
import com.nebula.salary.model.vo.PageResult;
import com.nebula.salary.model.vo.WorkOvertimeVo;
import com.nebula.salary.portal.mapper.WorkOvertimeMapper;
import com.nebula.salary.portal.service.IWorkOvertimeService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;

/**
 * <p>
 * 加班记录表 服务实现类
 * </p>
 *
 * @author codex
 * @since 2022-06-09
 */
@Service
public class WorkOvertimeServiceImpl extends ServiceImpl<WorkOvertimeMapper, WorkOvertime> implements IWorkOvertimeService {


    /**
     * 根据时间范围查询加班记录
     *
     * @param workOvertime 查询条件
     * @return WorkOvertimeVo集合
     */
    @Override
    public PageResult getRecord(WorkOvertimeDto workOvertime) {

        Page<WorkOvertimeVo> page = new Page<>(workOvertime.getPage(), workOvertime.getLimit());

        Long userId = SecurityUtil.getUserId();
        workOvertime.setUserId(userId);

        IPage<WorkOvertimeVo> pages = baseMapper.selectByPage(page, workOvertime);

        PageResult pageResult = new PageResult(pages.getTotal(), pages.getRecords().size(), pages.getRecords());

        return pageResult;
    }

    /**
     * 根据时间范围查询加班总天数
     *
     * @param workOvertime 查询条件
     * @return 加班总天数
     */
    @Override
    public BigDecimal getTotalWorkOvertimeDays(WorkOvertimeDto workOvertime) {
        Long userId = SecurityUtil.getUserId();
        workOvertime.setUserId(userId);
        return baseMapper.getTotalWorkOvertimeDays(workOvertime);
    }

    /**
     * 今年加班数
     *
     * @return 今年加班数
     */
    @Override
    public ServerResponse<BigDecimal> getYearCount() {
        BigDecimal count = baseMapper.getYearCount(LocalDateTime.now().getYear(), SecurityUtil.getUserId());
        return ServerResponse.createBySuccess(count);
    }

    /**
     * 加班打卡
     *
     * @param workOvertime 加班时间
     * @return 打卡结果
     */
    @Override
    public boolean clock(WorkOvertime workOvertime) {
        // 判断时间是否为空
        checkData(workOvertime);

        workOvertime.setUserId(SecurityUtil.getUserId());
        // 处理加班年份，方便统计， 例如：2021-12-21 ~ 2022-12-20 为一年的加班时间
        LocalDateTime startTime = workOvertime.getStartTime();
        int year = startTime.getYear();
        int monthValue = startTime.getMonthValue();
        int dayOfMonth = startTime.getDayOfMonth();
        if (monthValue == 12 && dayOfMonth >= 21){
            year += 1;
        }
        workOvertime.setYear(year);
        workOvertime.setDays(BigDecimal.valueOf(0.5));

        return baseMapper.insert(workOvertime) > 0;
    }

    /**
     * 删除加班记录
     *
     * @param recordIds 要删除的加班记录ID数组
     * @return 删除结果
     */
    @Override
    public ServerResponse<String> deleteRecords(Integer[] recordIds) {
        checkDataScope(recordIds);

        QueryWrapper<WorkOvertime> wrapper = new QueryWrapper<>();
        wrapper.eq(WorkOvertime.USER_ID, SecurityUtil.getUserId());
        wrapper.in(WorkOvertime.ID, recordIds);
        int result = baseMapper.delete(wrapper);

        return result > 0 ? ServerResponse.createBySuccessMessage(ReturnMessage.DELETE_SUCCESS)
                : ServerResponse.createByErrorMessage(ReturnMessage.DELETE_ERROR);
    }

    @Override
    public void checkDataScope(Integer[] recordIds) {
        Integer[] ids = baseMapper.getIdsByUserId(SecurityUtil.getUserId());

        if (!new HashSet<>(Arrays.asList(ids)).containsAll(Arrays.asList(recordIds))) {
            throw new ErrorException("无法操作非本人的加班记录");
        }
    }

    /**
     * 验证参数
     *
     * @param workOvertime 实体类
     */
    @Override
    public void checkData(WorkOvertime workOvertime) {
        if (workOvertime.getStartTime() == null) {
            throw new ErrorException("开始时间不能为空");
        }

        if (workOvertime.getEndTime() == null) {
            throw new ErrorException("结束时间不能为空");
        }

        if (workOvertime.getStartTime().isAfter(workOvertime.getEndTime())) {
            throw new ErrorException("开始时间不能大于结束时间");
        }

        QueryWrapper<WorkOvertime> wrapper = new QueryWrapper<>();
        wrapper.eq(WorkOvertime.START_TIME, workOvertime.getStartTime())
                .eq(WorkOvertime.END_TIME, workOvertime.getEndTime());

        Integer count = baseMapper.selectCount(wrapper);
        if (count > 0) {
            throw new ErrorException("请勿重复打卡");
        }
    }
}
